#!/bin/bash

# 体重K线图应用一键部署脚本
# 使用方法: bash deploy.sh [dev|prod]

set -e

MODE=${1:-dev}
PROJECT_NAME="weight-stock"

echo "🚀 开始部署体重K线图应用..."
echo "📦 部署模式: $MODE"

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# 打印带颜色的消息
print_status() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 检查Docker和Docker Compose
check_dependencies() {
    print_status "检查依赖..."
    
    if ! command -v docker &> /dev/null; then
        print_error "Docker 未安装，请先安装 Docker"
        exit 1
    fi

    if ! command -v docker-compose &> /dev/null; then
        print_error "Docker Compose 未安装，请先安装 Docker Compose"
        exit 1
    fi

    print_status "✅ 依赖检查通过"
}

# 清理旧容器
cleanup() {
    print_status "清理旧容器..."
    
    docker-compose -p $PROJECT_NAME down --remove-orphans 2>/dev/null || true
    docker system prune -f --volumes 2>/dev/null || true
    
    print_status "✅ 清理完成"
}

# 创建必要的目录和文件
setup_files() {
    print_status "设置配置文件..."
    
    # 创建MySQL初始化脚本目录
    mkdir -p mysql
    
    # 创建MySQL初始化脚本
    cat > mysql/init.sql << 'EOF'
-- 初始化数据库脚本
CREATE DATABASE IF NOT EXISTS weight_stock_db CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
USE weight_stock_db;

-- 设置时区
SET time_zone = '+08:00';

-- 创建示例用户（如需要）
-- CREATE USER 'weight_user'@'%' IDENTIFIED BY 'weight_pass';
-- GRANT ALL PRIVILEGES ON weight_stock_db.* TO 'weight_user'@'%';
-- FLUSH PRIVILEGES;
EOF

    # 创建后端环境变量文件
    if [ ! -f "backend/.env" ]; then
        cp backend/env.example backend/.env 2>/dev/null || cat > backend/.env << 'EOF'
PORT=3001
NODE_ENV=development
DB_HOST=mysql
DB_PORT=3306
DB_USER=root
DB_PASSWORD=Z159v677
DB_NAME=weight_stock_db
FRONTEND_URL=http://localhost:3000
JWT_SECRET=your_jwt_secret_here_change_in_production
EOF
    fi
    
    print_status "✅ 配置文件创建完成"
}

# 安装依赖
install_dependencies() {
    print_status "安装依赖..."
    
    # 安装根目录依赖
    if [ -f "package.json" ]; then
        npm install
    fi
    
    # 安装后端依赖
    if [ -d "backend" ] && [ -f "backend/package.json" ]; then
        cd backend
        npm install
        cd ..
    fi
    
    # 安装前端依赖
    if [ -d "frontend" ] && [ -f "frontend/package.json" ]; then
        cd frontend
        npm install
        cd ..
    fi
    
    print_status "✅ 依赖安装完成"
}

# 开发模式启动
dev_mode() {
    print_status "启动开发模式..."
    
    # 启动MySQL
    docker-compose up -d mysql
    
    print_status "等待MySQL启动..."
    sleep 10
    
    # 测试MySQL连接
    while ! docker-compose exec mysql mysqladmin ping -h"localhost" -uroot -pZ159v677 --silent 2>/dev/null; do
        print_warning "等待MySQL准备就绪..."
        sleep 3
    done
    
    print_status "✅ MySQL已启动"
    
    # 后台启动后端
    print_status "启动后端服务..."
    cd backend
    npm run dev &
    BACKEND_PID=$!
    cd ..
    
    # 等待后端启动
    sleep 5
    
    # 前台启动前端（用户可以看到输出）
    print_status "启动前端服务..."
    cd frontend
    npm start &
    FRONTEND_PID=$!
    cd ..
    
    print_status "🎉 开发环境启动完成!"
    print_status "📱 前端地址: http://localhost:3000"
    print_status "🔗 后端地址: http://localhost:3001"
    print_status "🗄️  数据库: localhost:3306"
    print_status ""
    print_status "按 Ctrl+C 停止所有服务"
    
    # 等待用户中断
    trap 'kill $BACKEND_PID $FRONTEND_PID 2>/dev/null; docker-compose stop mysql; exit 0' INT
    wait
}

# 生产模式启动
prod_mode() {
    print_status "启动生产模式..."
    
    # 构建和启动所有服务
    docker-compose -p $PROJECT_NAME up --build -d
    
    print_status "等待服务启动..."
    sleep 15
    
    # 检查服务状态
    if docker-compose -p $PROJECT_NAME ps | grep -q "Up"; then
        print_status "🎉 生产环境启动完成!"
        print_status "📱 应用地址: http://localhost:3000"
        print_status "🔗 API地址: http://localhost:3001"
        print_status ""
        print_status "查看日志: docker-compose -p $PROJECT_NAME logs -f"
        print_status "停止服务: docker-compose -p $PROJECT_NAME down"
    else
        print_error "服务启动失败，请检查日志"
        docker-compose -p $PROJECT_NAME logs
        exit 1
    fi
}

# 显示服务状态
show_status() {
    print_status "服务状态:"
    docker-compose -p $PROJECT_NAME ps
    
    print_status ""
    print_status "有用的命令:"
    echo "查看日志: docker-compose -p $PROJECT_NAME logs -f [service_name]"
    echo "重启服务: docker-compose -p $PROJECT_NAME restart [service_name]"
    echo "停止服务: docker-compose -p $PROJECT_NAME down"
    echo "进入容器: docker-compose -p $PROJECT_NAME exec [service_name] /bin/sh"
}

# 主执行流程
main() {
    case $MODE in
        "dev")
            check_dependencies
            setup_files
            install_dependencies
            dev_mode
            ;;
        "prod")
            check_dependencies
            cleanup
            setup_files
            prod_mode
            show_status
            ;;
        "status")
            show_status
            ;;
        "stop")
            print_status "停止所有服务..."
            docker-compose -p $PROJECT_NAME down
            print_status "✅ 服务已停止"
            ;;
        "clean")
            print_status "清理所有数据..."
            docker-compose -p $PROJECT_NAME down -v --remove-orphans
            docker system prune -f --volumes
            print_status "✅ 清理完成"
            ;;
        *)
            echo "使用方法: bash deploy.sh [dev|prod|status|stop|clean]"
            echo ""
            echo "选项:"
            echo "  dev     - 开发模式启动"
            echo "  prod    - 生产模式启动 (Docker)"
            echo "  status  - 查看服务状态"
            echo "  stop    - 停止所有服务"
            echo "  clean   - 清理所有数据"
            exit 1
            ;;
    esac
}

# 执行主函数
main
